<?php
session_start();
$user= isset($_SESSION["user"])?$_SESSION["user"]:null;

function makePageUrl($i){
    $querString = $_SERVER["QUERY_STRING"];
    if(preg_match('/pageIndex=\d+/',$querString)){
        $querString = preg_replace('/pageIndex=\d+/','pageIndex='.$i,$querString);
    }else {
        $querString .= "&pageIndex=$i";
    }
    return $querString;
  }
  $theme = isset($_GET["theme"])?$_GET["theme"]:null;
if(!$theme){
  $theme = $_COOKIE["theme"];
}else{
  setcookie("theme",$theme);
}
if(!$theme) $theme = "default";

function getParam($name){
    $value = isset($_GET[$name])?trim($_GET[$name]):"";
    $value = str_replace("'","''",$value);
    return $value;

}

function creatDb(){
  return new mysqli("localhost","root","root","php");
}

function pageable($tbname,$where,$order,$pageIndex,$pageSize){
  $start = ($pageIndex-1)*$pageSize;
  $conn = creatDb();
  $itemssql = "SELECT * FROM `$tbname`";
  if($where) $itemssql.=" WHERE ".$where;
  if($order) $itemssql.=" ORDER By ".$order;
  $itemssql.=" LIMIT $start,$pageSize ";
  $rs = $conn->query($itemssql);
  $items = [];
  while($record = $rs->fetch_assoc()) $items[]=$record;
  $rs->close();

  $countSql = "SELECT count(*) as c FROM `$tbname`";
  if($where) $countSql.=" WHERE ".$where;
  $rs = $conn->query($countSql);
  $total = $rs->fetch_assoc()["c"];
  $rs->close();
  $pageCount = ceil($total/$pageSize);
return[
  "items"=>$items,
  "total"=>$total,
  "pageCount"=>$pageCount
];

}



